package com.swagger.demo.threads;

import org.springframework.format.annotation.DateTimeFormat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @auther heyang
 * @date 2020/9/16 21:53
 */
public class MyRunnable implements Runnable {
    //private volatile int ticket = 10; //volatile关键字 不能解决线程不安全的问题
    // private int ticket = 10;
    private AtomicInteger ticket = new AtomicInteger(10);
    private SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //同步锁
    private ReentrantLock lock = new ReentrantLock(true); //true 表示公平锁

    @Override
    public void run() {
        //同步方法
        //同步代码块 this代表当前的锁得资源
//        synchronized (this) {
//        buy();
//        }
      /*  try {
            lock.lock();
            buy();
        } finally {
            //解锁
            lock.unlock();
        }*/
        buy();
    }

/*    public void buy() {

        for (int i = ticket; ticket > 0; ticket--)
            System.out.println(Thread.currentThread().getName() + "抢到票" + ticket + "--时间:" + date.format(new Date().getTime()));
    }*/

    public void buy() {

        for (AtomicInteger i = ticket; ticket.get() > 0; ticket.getAndDecrement())
            System.out.println(Thread.currentThread().getName() + "抢到票" + ticket + "--时间:" + date.format(new Date().getTime()));
    }
}
